package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
)

type BrowseController struct {
}

func BrowseRegister(group *gin.RouterGroup) {
	browse := &BrowseController{}
	//浏览记录新增
	group.POST("/add", browse.Add)
	//浏览记录详情
	group.GET("/detail", browse.Detail)
	//浏览记录列表
	group.GET("/page", browse.Page)
	//浏览记录删除
	group.POST("/remove", browse.Remove)
}

func (co *BrowseController) Add(c *gin.Context) {
	params := &dto.BrowseInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	browse := &dao.Browse{
		SiteId:    params.SiteId,
		CreatedBy: fmt.Sprintf("%v", value),
	}
	browse.InitData(tx)
	//先查询是否已经浏览记录过了
	if result := tx.Where("is_delete = 0 AND site_id = ? AND created_by = ?", params.SiteId, value).First(browse); result.RowsAffected != 0 {
		middleware.ResponseSuccess(c, "操作成功", true)
		return
	}
	if err := browse.Save(c, tx); err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (co *BrowseController) Detail(c *gin.Context) {
	params := &dto.BrowseDetailInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if params.Id == "" && params.SiteId == "" {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	browse := &dao.Browse{}
	query := tx.Model(&dao.Browse{}).Where("is_delete = 0")
	if params.SiteId != "" {
		query = query.Where("site_id = ? AND created_by = ?", params.SiteId, value)
	} else {
		query = query.Where("id = ?", params.Id)
	}
	query.First(browse)
	middleware.ResponseSuccess(c, browse, true)
}
func (co *BrowseController) Page(c *gin.Context) {
	params := &dto.BrowsePageInput{}
	if err := params.BindValidParam(c); err != nil {
		fmt.Println(err)
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Browse
	query := tx.WithContext(c).Model(&dao.Browse{}).Select("browse.site_id,browse.create_at,browse.id,browse.created_by,browse.status,browse.is_delete,site.status,site.is_delete,site.status,site.name,site.address,site.image,site.max_people_num,site.facilities,site.phone,site.business").Joins("left join site on site.id = browse.site_id").Where("browse.is_delete = 0 AND browse.created_by = ?  AND site.status <> 1 AND site.is_delete = 0", value).Order("create_at desc")

	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Scan(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	out := &dto.BrowsePageOutput{
		Total: total,
	}
	for _, item := range list {
		//查询场地详细信息
		site := &dao.Site{}
		tx.Where("is_delete = 0 AND status <> 1 AND id = ?", item.SiteId).First(site)
		if site.Id != 0 {
			out.List = append(out.List, dto.BrowseInfo{
				Id:           fmt.Sprintf("%d", item.Id),
				SiteId:       item.SiteId,
				Name:         site.Name,
				Address:      site.Address,
				Image:        site.Image,
				MaxPeopleNum: site.MaxPeopleNum,
				Facilities:   string(site.Facilities),
				Phone:        site.Phone,
				Service:      string(site.Service),
				Business:     site.Business,
				CreatedAt:    item.CreatedAt.Format("2006-01-02 15:04:05"),
			})
		}
	}
	middleware.ResponseSuccess(c, out, true)
}
func (co *BrowseController) Remove(c *gin.Context) {
	params := &dto.BrowseRemoveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Browse{}).Where(map[string]interface{}{
		"id":         params.Id,
		"created_by": value,
	}).Update("is_delete", 1); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
